package A1_二叉树;

public class LC_222完全二叉树的节点个数_完全二叉树 {
    public static class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(){}
        TreeNode(int val){
            this.val=val;
        }
        TreeNode(int val, TreeNode left, TreeNode right){
            this.val=val;
            this.left=left;
            this.right=right;
        }
    }
    public static void main(String[] args){
        TreeNode root=new TreeNode(1);
        root.left=new TreeNode(2);
        root.right=new TreeNode(3);
        root.left.left=new TreeNode(4);
        root.left.right=new TreeNode(5);
        root.right.left=new TreeNode(6);
        System.out.println(countNodes(root));
    }
    public static int countNodes(TreeNode root) {
        if(root==null)
            return 0;
        TreeNode left=root.left;
        TreeNode right=root.right;
        int leftdepth=0,rightdepth=0;
        while(left!=null){
            left=left.left;
            leftdepth++;
        }
        while(right!=null){
            right=right.right;
            rightdepth++;
        }
        if(rightdepth==leftdepth)
//            return Integer.parseInt(String.valueOf(Math.pow(2,leftdepth)))-1;
            return (2<<leftdepth)-1;//注意此处
        int leftnum=countNodes(root.left);
        int rightnum=countNodes(root.right);
        return leftnum+rightnum+1;
    }
}
